<template>
  <div id="container" v-loading="fullscreenLoading"></div>
</template>


<script language="javascript">
  import { listFactory } from "@/api/basic/factory/factory";
  export default {
    data() {
      return {
        // 查询参数
        queryParams: {
          pageNum: 30,
        },
        fullscreenLoading: true,
      };
    },
    created() { },
    methods: {
      /** 查询工厂基础信息列表 */
      getList() {
        let center = [120.54496, 36.222742];
        listFactory(this.queryParams).then((response) => {
          this.factoryList = response.rows;
          this.fullscreenLoading = false;
          this.$nextTick(() => {
            if (response.rows.length > 0) {
              // center = [];
              // center.push(response.rows[0].lng);
              // center.push(response.rows[0].lat);
            }
            this.initMap(center);
            // console.log(response.rows);
          }).catch((error) => {
            this.common.thisError(error);
            this.initMap(center);
            this.fullscreenLoading = false;
          });
        });
      },
      // 实例化地图
      initMap(center) {
        // var map = new AMap.Map("container", {
        //   center: center,
        //   // disableSocket: true,
        //   // viewMode: "3D",
        //   // showLabel: false,
        //   // labelzIndex: 130,
        //   // pitch: 40,
        //   // mapStyle: "amap://styles/blue",
        //   // zoom: 11.6,

        // });
        AMapUI.loadUI(['geo/DistrictExplorer'], function (DistrictExplorer) {

          // 启动页面
          initPage(DistrictExplorer);

          function initPage(DistrictExplorer) {
            // 创建地图实例
            var map = new AMap.Map('container', {
              zoom: 4,
              center: [104.114129, 37.550339]
            });

            // 创建DistrictExplorer实例
            var districtExplorer = new DistrictExplorer({
              map: map
            });

            var currentAreaNode = null;

            // 加载全国的区划节点
            loadAreaNode(100000);

            // 加载区划节点并渲染
            function loadAreaNode(adcode) {
              districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
                if (error) {
                  console.error(error);
                  return;
                }

                currentAreaNode = areaNode;

                // 渲染区划
                renderAreaNode(areaNode);
              });
            }

            // 渲染区划节点
            function renderAreaNode(areaNode) {
              // 清除已有的绘制内容
              districtExplorer.clearFeaturePolygons();

              // 设定不同区划的颜色
              var colors = ["#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00"];

              // 渲染子级区划
              districtExplorer.renderSubFeatures(areaNode, function (feature, i) {
                var fillColor = colors[i % colors.length];
                var strokeColor = colors[colors.length - 1 - i % colors.length];

                return {
                  cursor: 'pointer',
                  bubble: true,
                  strokeColor: strokeColor,
                  strokeOpacity: 1,
                  strokeWeight: 1,
                  fillColor: fillColor,
                  fillOpacity: 0.35,
                };
              });

              // 渲染父级区划
              districtExplorer.renderParentFeature(areaNode, {
                cursor: 'default',
                bubble: true,
                strokeColor: 'black',
                fillColor: null,
                strokeWeight: 3,
              });

              // 更新视野
              map.setFitView(districtExplorer.getAllFeaturePolygons());
            }

            // 监听鼠标移入事件，实现高亮
            districtExplorer.on('featureMouseout featureMouseover', function (e, feature) {
              var isMouseOver = e.type === 'featureMouseover';

              if (!feature) {
                return;
              }

              var props = feature.properties;

              var polys = districtExplorer.findFeaturePolygonsByAdcode(props.adcode);

              for (var i = 0; i < polys.length; i++) {
                polys[i].setOptions({
                  fillOpacity: isMouseOver ? 0.7 : 0.35
                });
              }
            });

            // 监听点击事件，实现下钻
            districtExplorer.on('featureClick', function (e, feature) {
              if (!feature) {
                return;
              }

              var props = feature.properties;

              // 加载点击的区域的下级区划
              if (props.childrenNum > 0) {
                loadAreaNode(props.adcode);
              }
            });
          }
        });
        return false


        var _this = this;
        var opts = {
          subdistrict: 0,
          extensions: "all",
          level: "city",
        };
        //利用行政区查询获取边界构建mask路径
        //也可以直接通过经纬度构建mask路径
        var district = new AMap.DistrictSearch(opts);
        district.search("崂山区", function (status, result) {
          var bounds = result.districtList[0].boundaries;
          var mask = [];
          for (var i = 0; i < bounds.length; i += 1) {
            mask.push([bounds[i]]);
          }
          var map = new AMap.Map("container", {
            center: center,
            disableSocket: true,
            viewMode: "3D",
            showLabel: false,
            labelzIndex: 130,
            pitch: 40,
            mapStyle: "amap://styles/blue",
            zoom: 11.6,
            layers: [
              new AMap.TileLayer.RoadNet({
                //rejectMapMask:true
              }),
              new AMap.TileLayer.Satellite(),
            ],
          });
          //var maskerIn = new AMap.Marker({
          //   position:[120.46803,36.10811],
          // map:map
          //})
          var data = _this.factoryList;
          var lnglats = [];

          for (var i in data) {
            var position = [];
            if (data[i].lat != null) {
              position.push(Number(data[i].lng));
              position.push(Number(data[i].lat));
              lnglats.push({
                title: data[i].name,
                address: data[i].address == null ? "- -" : data[i].address,
                position: position,
                peopleNum: data[i].peopleNum == null ? "- -" : data[i].peopleNum,
                scale: data[i].scale == null ? "- -" : data[i].scale,
                fundNum: data[i].fundNum == null ? "- -" : data[i].fundNum,
                leader: data[i].leader == null ? "- -" : data[i].leader,
                phone: data[i].phone == null ? "- -" : data[i].phone,
                desc: data[i].desc == null ? "- -" : data[i].desc,
                pic:
                  data[i].pic == null || data[i].pic == "" ? "- -" : data[i].pic,
              });
            }
          }
          var clickEventListener = map.on("click", function (e) {
            // document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
            // console.log(e)
          });
          // 创建一个 Icon
          var startIcon = new AMap.Icon({
            // 图标尺寸
            // size: new AMap.Size(25, 34),
            // 图标的取图地址
            image: require("@/assets/images/mark.png"),
            // 图标所用图片大小
            // imageSize: new AMap.Size(135, 40),
            // 图标取图偏移量
            // imageOffset: new AMap.Pixel(-9, -3)
          });
          var infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -30),
          });
          for (var i = 0, marker; i < lnglats.length; i++) {
            var marker = new AMap.Marker({
              position: lnglats[i].position,
              icon: startIcon,
              map: map,
              extData: {
                markertitle: lnglats[i].title,
                markerAddress: lnglats[i].address,
              },
            });
            // console.log(marker.getExtData(), "测试1111111111111");
            var title = marker.getExtData().markertitle;
            var address = marker.getExtData().markerAddress;
            // marker.content = title + "\n" + address;

            // (marker.content =
            //   "<div class='de'>名称: " +
            //   title +
            //   "</div>" +
            //   "<div class='de'>地址: " +
            //   address +
            //   "</div>" +
            //   "<div class='de'>人数: " +
            //   lnglats[i].peopleNum +
            //   "" +
            //   "； &nbsp;规模: " +
            //   lnglats[i].scale +
            //   "；&nbsp;资金: " +
            //   lnglats[i].fundNum +
            //   "</div>" +
            //   "<div class='de'>负责人: " +
            //   lnglats[i].leader +
            //   "； &nbsp;联系方式: " +
            //   lnglats[i].phone +
            //   "</div>" +
            //   "<div class='de'>工厂描述: " +
            //   lnglats[i].desc +
            //   "</div>" +
            //   "<div class='de'> <img style='width:100%;cursor: pointer;' src='" +
            //   lnglats[i].pic +
            //   "' /></div>"), //设置文本标注内容
            (marker.value = {
              title: title,
              address: address,
              peopleNum: lnglats[i].peopleNum,
              scale: lnglats[i].scale,
              fundNum: lnglats[i].fundNum,
              leader: lnglats[i].leader,
              phone: lnglats[i].phone,
              pic: lnglats[i].pic,
            }),
              // marker.content = "第" + (i + 1) + "个Marker";
              marker.on("click", markerClick);
            // marker.setTitle('我是marker的title');
            marker.setLabel({
              offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
              content:
                "<div class='info'>" +
                (i + 1) +
                "." +
                lnglats[i].title +
                "</div>", //设置文本标注内容
              direction: "top", //设置文本标注方位
            });
            // console.log(111)
          }
          // marker.setTitle('我是marker的title');

          function markerClick(e, val) {
            // console.log(e.target.value);
            _this.$emit("openMap", e.target.value);
            infoWindow.setContent(e.target.content);
            infoWindow.open(map, e.target.getPosition());
          }
          //var maskerOut = new AMap.Marker({//区域外的不会显示
          //    map:map
          // })
          //添加描边
          for (var i = 0; i < bounds.length; i += 1) {
            new AMap.Polyline({
              path: bounds[i],
              // strokeColor: "#01b0f3",
              strokeColor: "#00baff",
              strokeWeight: 4,
              strokeOpacity: 1, //线透明度
              // fillColor: "red", //填充色
              // fillOpacity: 0.35, //填充透明度
              map: map,
            });
          }
        });
      },
      //打开图片
      bigImg(e) {
        console.log(e);
      },
    },
    async mounted() {
      // var _this = this;
      // setTimeout(() => {
      //   this.initMap();
      // }, 200);
      // window["bigImg"] = (result) => {
      //   this.bigImg(result);
      // };
      await this.$nextTick(() => {
        this.getList();
      });
    },
  };
</script>
<style>
  body,
  html,
  #container {
    margin: 0;
    width: 100%;
    height: 110%;
  }

  .info {
    background: rgba(34, 101, 92, 0.55);
    color: #ffffff;
    padding: 5px 7px;
  }

  .amap-marker-label {
    border: 1px solid rgba(0, 0, 0, 0);
    background-color: rgba(0, 0, 0, 0);
  }

  .amap-info-content {
    background-color: rgba(9, 59, 118, 0.85);
    /* opacity: 0.75; */
    /* background-color: #42a9ff; */
    border: 1px solid #42a9ff;
    width: 350px;
    color: white;
  }

  .amap-info-close {
    top: 1px;
    right: 2px !important;
  }

  .amap-info-content {
    padding: 10px 12px 10px 12px;
  }

  .de {
    background: rgba(88, 134, 127, 0);
    color: #ffffff;
    font-size: 12px;
    padding: 0;
  }
</style>
